include("shared.lua")
include("sh_player.lua")
include("nightvision.lua")
name=""
money=""
doors={[0]="None"}
function GetName(inf)
	name=inf:ReadString()
end
usermessage.Hook("GetName",GetName)
function GetCred(inf)
	money=inf:ReadString()
end
usermessage.Hook("GetCred",GetCred)

function GetDInfo(handle, id, encoded, decoded)
	doors=decoded
end
datastream.Hook("GetDInfo",GetDInfo)

local function AddToChat(msg)
	local text=msg:ReadString()
	local ply=msg:ReadString()
	if text and text ~= "" then
		chat.AddText(col1,ply,": "..text)
		hook.Call("OnPlayerChat",GM,ply,text,false,LocalPlayer():Alive())
	end
end
usermessage.Hook("ChatMsg",AddToChat)

-- HUD --
function myhud()
	local ply=LocalPlayer()
	if !ply:Alive() then return end
	if(ply:GetActiveWeapon()==NULL or ply:GetActiveWeapon()=="Camera") then return end
	local X=ScrW()-205
	if ply:Team()<8 then
		draw.RoundedBox(6,X,5,200,110,Color(126,128,128,255))
		draw.DrawText("Name: "..name,"ScoreboardText",X+10,10,Color(255,255,255,255),0)
		draw.DrawText("CID: "..ply:UniqueID(),"ScoreboardText",X+10,30,Color(255,255,255,255),0)
		draw.DrawText("Role: "..team.GetName(ply:Team()),"ScoreboardText",X+10,50,Color(255,255,255,255),0)
		draw.DrawText("Health: "..ply:Health(),"ScoreboardText",X+10,70,Color(255,255,255,255),0)
		draw.DrawText("Credits: "..money,"ScoreboardText",X+10,90,Color(255,255,255,255),0)
	elseif ply:Team()>=8 then
		draw.RoundedBox(6,X,5,200,70,Color(126,128,128,255))
		draw.DrawText("Unit Number: "..ply:UniqueID(),"ScoreboardText",X+10,10,Color(255,255,255,255),0)
		draw.DrawText("Health: "..ply:Health(),"ScoreboardText",X+10,30,Color(255,255,255,255),0)
		draw.DrawText("Role: "..team.GetName(ply:Team()),"ScoreboardText",X+10,50,Color(255,255,255,255),0)
	end
	local tr=ply:GetEyeTraceNoCursor()
	if(tr.Entity:GetClass()=="prop_door_rotating")and(doors[tr.Entity:EntIndex()]!=nil)and(ply:EyePos():Distance(tr.Entity:GetPos())<100)then
		if (doors[tr.Entity:EntIndex()]=="None") then
			draw.DrawText("Not Owned.\nBuy for 20 credits.","ScoreboardText",ScrW()/2,(ScrH()/2)-25,Color(0,0,0,255),1)
		else
			local name=player.GetByUniqueID(doors[tr.Entity:EntIndex()]):Nick()
			draw.DrawText("Owned by:\n"..name,"ScoreboardText",ScrW()/2,(ScrH()/2)-25,Color(0,0,0,255),1)
		end
	else
		return
	end
end
hook.Add("HUDPaint","myhud",myhud)

function DoorMenu()
	local tr=LocalPlayer():GetEyeTraceNoCursor()
	if LocalPlayer():EyePos():Distance(tr.Entity:GetPos())<65 then
		if(tr.Entity:GetClass()!="prop_door_rotating")or(doors[tr.Entity:EntIndex()]=="None")or(doors[tr.Entity:EntIndex()]==LocalPlayer():UniqueID()) then
			local DoorPanel=vgui.Create("DFrame")
			DoorPanel:SetSize(150,100)
			DoorPanel:SetTitle("RP Doors")
			DoorPanel:SetVisible(true)
			DoorPanel:SetDraggable(false)
			DoorPanel:ShowCloseButton(true)
			DoorPanel:MakePopup()
			DoorPanel:Center()
			NoCloseMenu=CurTime()+0.6
			function DoorPanel:Think()
				if input.IsKeyDown(KEY_F4) and NoCloseMenu<CurTime() then
					self:Close()
				end
			end
			local BuySell=vgui.Create("DButton",DoorPanel)
			BuySell:SetPos(25,25)
			BuySell:SetSize(100,30)
			local text=""
			if(doors[tr.Entity:EntIndex()]=="None") then text="Buy" elseif(doors[tr.Entity:EntIndex()]==LocalPlayer():UniqueID()) then text="Sell" end
			BuySell:SetText(text)
			BuySell.DoClick=function(button)
				RunConsoleCommand("rp_doortoggle")
			end
			local SellAll=vgui.Create("DButton",DoorPanel)
			SellAll:SetPos(25,65)
			SellAll:SetSize(100,25)
			SellAll:SetText("Sell All Doors")
			SellAll.DoClick=function(button)
				RunConsoleCommand("rp_SellDoors")
			end
		else
			LocalPlayer():ChatPrint("You need to be looking at a door that you own/isn't already owned.")
			return false
		end
	end
end
concommand.Add("rp_doors",DoorMenu)

function GM:HUDDrawTargetID()
	local tr=utilx.GetPlayerTrace(LocalPlayer(),LocalPlayer():GetCursorAimVector())
	local trace = util.TraceLine(tr)
	if(!trace.Hit)then return end
	if(!trace.HitNonWorld)then return end
	if trace.Entity:IsPlayer() then
		local ply=trace.Entity
		local x=ScrW()/2
		local y=ScrH()/2
		draw.DrawText(ply:GetNWString("rpname"),"ScoreboardText",x,y+25,team.GetColor(ply:Team()),1)
	end
	return false
end

-- Hide health & battery HUD --
function hidehud(name)
	for k,v in pairs{"CHudHealth","CHudBattery"} do
		if name==v then return false end
	end
end
hook.Add("HUDShouldDraw", "hidehud", hidehud)

-- Hide death/kill notices --
function GM:DrawDeathNotice(x,y)
	return
end

-- F4 Menu --
function MenuFrame(ply)
	MenuPanel=vgui.Create("DFrame")
	MenuPanel:SetSize(800,600)
	MenuPanel:SetTitle("deRP Menu")
	MenuPanel:SetVisible(true)
	MenuPanel:SetDraggable(false)
	MenuPanel:ShowCloseButton(true)
	MenuPanel:MakePopup()
	MenuPanel:Center()
	NoCloseMenu=CurTime()+0.6
	function MenuPanel:Think()
		if input.IsKeyDown(KEY_F4) and NoCloseMenu<CurTime() then
			self:Close()
		end
	end
	PropertySheet=vgui.Create("DPropertySheet")
	PropertySheet:SetParent(MenuPanel)
	PropertySheet:SetPos(3,25)
	PropertySheet:SetSize(794,575)

	TeamTab=vgui.Create("DPanel")
	TeamTab:SetVisible(true)

	JobDesc=vgui.Create("DLabel",TeamTab)
	JobDesc:SetPos(120,5)
	JobDesc:SetTextColor(Color(0,0,0,255))
	JobDesc:SizeToContents()
	JobDesc:SetText("")
	
	icon=vgui.Create("DModelPanel",TeamTab)
	icon:SetSize(150,150)
	icon:SetPos(644,30)
	function icon:LayoutEntity()
		self:RunAnimation()
	end
	icon:SetCamPos(Vector(50,80,80))
	icon:SetLookAt(Vector(0,0,50))
	icon:SetModel("")
	
	-- Create a button for each job --
	for ID,TeamInfo in SortedPairs(team.GetAllTeams()) do
		if(TeamInfo.Name!="Joining/Connecting")and(TeamInfo.Name!="Unassigned")and(TeamInfo.Name!="Spectator")then
		RunString("local b_"..ID.."=vgui.Create(\"DButton\",TeamTab)\nb_"..ID..":SetSize(100,25)\nb_"..ID..":SetPos(7,"..(30*ID)-25 ..")\nb_"..ID..":SetText(\""..TeamInfo.Name.."\")\nb_"..ID..".OnCursorEntered=function()\nJobDesc:SetText(tostring(Jobs["..ID.."][3]))\nJobDesc:SizeToContents() \nicon:SetModel(\""..Jobs[ID][1].."\")\nend\nb_"..ID..".OnCursorExited=function()\nJobDesc:SetText(\"\")\nicon:SetModel(\"\")\nend\nb_"..ID..".DoClick=function(button)\nRunConsoleCommand(\"rp_job\",\""..ID.."\")\nMenuPanel:Close()\nend")
		end
	end
	
	ToolsTab=vgui.Create("DPanel")
	ToolsTab:SetVisible(true)
	plyName=vgui.Create("DTextEntry",ToolsTab)
	plyName:SetText(name)
	plyName:SetPos(3,5)
	plyName:SetSize(120,20)
	plyName.OnEnter=function() RunConsoleCommand("rp_name", plyName:GetValue()) end
	local b_name=vgui.Create("DButton",ToolsTab)
	b_name:SetText("Change Name")
	b_name:SetSize(80,20)
	b_name:SetPos(126,5)
	b_name.DoClick=function(button) RunConsoleCommand("rp_name", plyName:GetValue()) end
	
	ItemTab=vgui.Create("DPanel")
	ItemTab:SetVisible(true)
	for k,v in pairs(JobItems[LocalPlayer():Team()]) do
		RunString("b_"..k.."=vgui.Create(\"DButton\",ItemTab)\nb_"..k..":SetText(\""..v[3].."\")\nb_"..k..":SetSize(100,25)\nb_"..k..":SetPos(7,"..(30*k)-25 ..")\nb_"..k..".OnCursorEntered=function() ItemDesc:SetText(\""..v[4].."\")\nItemDesc:SizeToContents()\nend\nb_"..k..".OnCursorExited=function() ItemDesc:SetText(\"\") end\nb_"..k..".DoClick=function()\nRunConsoleCommand(\"rp_buy\",\""..v[1].."\")\nend")
	end
	ItemDesc=vgui.Create("DLabel",ItemTab)
	ItemDesc:SetPos(120,5)
	ItemDesc:SetTextColor(Color(0,0,0,255))
	ItemDesc:SizeToContents()
	ItemDesc:SetText("")
	
	HelpTab=vgui.Create("DPanel")
	HelpTab:SetVisible(true)
	local HelpText=vgui.Create("DLabel",HelpTab)
	HelpText:SetPos(5,5)
	HelpText:SetTextColor(Color(0,0,0,255))
	HelpText:SetText([[Welcome to deRP!
	deRP is a Half-Life 2 style roleplay gamemode.
	
	New Life Rule (NLR)
		New Life Rule means that when you die you foreget how you died. As such anyone returning to their place of death without reason
		will be warned/kicked. Revenge killing will result in being kicked.
	
	Weapons
		Weapons are deemed as ilegal and as such, citizens found with them will be shot on sight by Combine/Civil Protection.
		To holster/lower a weapon hold 'e' (use key) and left click (primary fire).
	
	Chat
		Out Of Character (OOC):
		To chat OOC type // and a space before your message. OOC chat is out of character and as such should not be acted upon in game.
		However do not discus what you wouldn't want an opposing team to know in OOC for example a rebel hideout, because the combine
		may decide to search there next... Go figure.
		
		In Character:
		In character chat is default in game. Please try to keep your character in this chat, i.e. Citizens fear all Combine etc.
	]])
	HelpText:SizeToContents()
	PropertySheet:AddSheet("Jobs",TeamTab,"gui/silkicons/group",false,false,"Jobs")
	PropertySheet:AddSheet("Actions",ToolsTab,"gui/silkicons/user",false,false,"Actions")
	PropertySheet:AddSheet("Items",ItemTab,"gui/silkicons/box",false,false,"Items")
	PropertySheet:AddSheet("Help",HelpTab,"gui/silkicons/magnifier",false,false,"Help")
end
concommand.Add("rp_menu",MenuFrame)

-- Help Menu --
function HelpFrame()
	LocalPlayer():ChatPrint("RP Help is in the F4 Menu")
end
concommand.Add("rp_help",HelpFrame)

-- Voices Menu --
function VoiceFrame()
	if (LocalPlayer():Team()==8||LocalPlayer():Team()==9||LocalPlayer():Team()==10) then
		Text={"Move","Affirmative","Move along","I said move along","Move back! Right now!","Don't move","First warning, move away","This is your second warning","Final warning","You, citizen, come with me","Hold it right there","Take him down!","Overwatch, advise, we have heavy resistance","Officer under fire, taking cover","Officer needs help","Now get out of here","Alright, you can go","Citizen","Cover me, I'm going in","Get outa here","Move it!","11-99 Officer needs assistance","Copy","Rodger that","You want a malcompliance verdict?"}
		Sound={"npc/metropolice/vo/move.wav","npc/metropolice/vo/affirmative.wav","npc/metropolice/vo/movealong3.wav","npc/metropolice/vo/isaidmovealong.wav","npc/metropolice/vo/movebackrightnow.wav","npc/metropolice/vo/dontmove.wav","npc/metropolice/vo/firstwarningmove.wav","npc/metropolice/vo/thisisyoursecondwarning.wav","npc/metropolice/vo/finalwarning.wav","vo/trainyard/ba_youcomewith.wav","npc/metropolice/vo/holditrightthere.wav","npc/metropolice/takedown.wav","npc/combine_soldier/vo/heavyresistance.wav","npc/metropolice/vo/officerunderfiretakingcover.wav","npc/metropolice/vo/officerneedshelp.wav","npc/metropolice/vo/nowgetoutofhere.wav","npc/metropolice/vo/allrightyoucango.wav","npc/metropolice/vo/citizen.wav","npc/metropolice/vo/covermegoingin.wav","npc/metropolice/vo/getoutofhere.wav","npc/metropolice/vo/moveit.wav","npc/metropolice/vo/11-99officerneedsassistance.wav","npc/metropolice/vo/copy.wav","npc/metropolice/vo/rodgerthat.wav","npc/metropolice/vo/youwantamalcomplianceverdict.wav"}
	else
		Text={"Good God","NOOO!","Excuse me","OK","Get the hell outa here!","Help!","Sorry","Yeah","Hi","CP's","Pardon me","Can't you see I'm busy?","Get outa here","Fantastic","RUUUUN!","Thats you all over","Can we talk about this later?","Have you ever had an original thought?","Oops"}
		Sound={"/vo/npc/male01/goodgod.wav","vo/npc/male01/no02.wav","/vo/npc/male01/excuseme01.wav","vo/npc/male01/ok01.wav","/vo/npc/male01/gethellout.wav","vo/npc/male01/help01.wav","vo/npc/male01/sorry01.wav","vo/npc/male01/yeah02.wav","vo/npc/male01/hi01.wav","vo/npc/male01/cps01.wav","vo/npc/male01/pardonme01.wav","vo/npc/male01/busy02.wav","vo/canals/boxcar_go_nag03.wav","vo/npc/male01/fantastic01.wav","vo/npc/male01/strider_run.wav","vo/npc/male01/answer01.wav","vo/npc/male01/answer05.wav","vo/npc/male01/answer16.wav","vo/npc/male01/whoops01.wav"}
	end
	VoicePane=vgui.Create("DFrame")
	VoicePane:SetSize(200,600)
	VoicePane:SetTitle("RP Voices")
	VoicePane:SetVisible(true)
	VoicePane:SetDraggable(false)
	VoicePane:ShowCloseButton(true)
	VoicePane:MakePopup()
	VoicePane:AlignLeft(10)
	VoicePane:AlignTop(ScrH()/2-300)
	NoCloseMenu=CurTime()+0.6
	function VoicePane:Think()
		if input.IsKeyDown(KEY_F3) and NoCloseMenu<CurTime() then
			self:Close()
		end
	end
	local tot=table.getn(Text)
	ButtonPanel=vgui.Create("DPanelList",VoicePane)
	ButtonPanel:SetPos(5,25)
	ButtonPanel:SetSize(190,565)
	ButtonPanel:EnableVerticalScrollbar(true)
	ButtonPanel:SetSpacing(3)
	ButtonPanel:EnableHorizontal(false)
	
	if(table.getn(Text)!=table.getn(Sound)) then
		Msg("Tables unmatched, expect errors...")
		error("Tables unmatched, expect errors...")
	end
	for i=1,tot do
	RunString("local b_"..i.."=vgui.Create(\"DButton\")\nb_"..i..":SetPos(0,"..36*(i-1)..")\nb_"..i..":SetText(\""..Text[i].."\")\nb_"..i..".DoClick=function()\nRunConsoleCommand(\"rp_voice\",\""..Text[i].."\",\""..Sound[i].."\")\nVoicePane:Close()\nend\nButtonPanel:AddItem(b_"..i..")")
	end
end
concommand.Add("rp_voices",VoiceFrame)